﻿#include "mainholdwidget.h"
#include<QMessageBox>

MainHoldWidget::MainHoldWidget(QWidget *parent) :
    QWidget(parent)
{
    setupModel();
    setupViews();
}

void MainHoldWidget::setupModel()
{
    m_modelHold = new QStandardItemModel(0, 14, this);
    m_modelHold->setHeaderData(0, Qt::Horizontal, QStringLiteral("资金账号"));
    m_modelHold->setHeaderData(1, Qt::Horizontal, QStringLiteral("合约代码"));
    m_modelHold->setHeaderData(2, Qt::Horizontal, QStringLiteral("持仓多空方向"));
    m_modelHold->setHeaderData(3, Qt::Horizontal, QStringLiteral("投机套保标志"));
    m_modelHold->setHeaderData(4, Qt::Horizontal, QStringLiteral("持仓日期"));
    m_modelHold->setHeaderData(5, Qt::Horizontal, QStringLiteral("上日持仓"));
    m_modelHold->setHeaderData(6, Qt::Horizontal, QStringLiteral("今日持仓"));
    m_modelHold->setHeaderData(7, Qt::Horizontal, QStringLiteral("开仓量"));
    m_modelHold->setHeaderData(8, Qt::Horizontal, QStringLiteral("平仓量"));
    m_modelHold->setHeaderData(9, Qt::Horizontal, QStringLiteral("开仓金额"));
    m_modelHold->setHeaderData(10, Qt::Horizontal, QStringLiteral("平仓金额"));
    m_modelHold->setHeaderData(11, Qt::Horizontal, QStringLiteral("平仓盈亏"));
    m_modelHold->setHeaderData(12, Qt::Horizontal, QStringLiteral("持仓盈亏"));
    m_modelHold->setHeaderData(13, Qt::Horizontal, QStringLiteral("占用的保证金"));
}

void MainHoldWidget::setupViews()
{
    hboxlayout = new QHBoxLayout;
    QLabel* accountLabel = new QLabel(QStringLiteral("资金账号"));
    m_accountCombox = new QComboBox;
    m_querybutton = new QPushButton(QStringLiteral("查询"));
    m_exportbutton = new QPushButton(QStringLiteral("导出"));
    accountLabel->setFixedWidth(80);
    m_accountCombox->setFixedWidth(100);
    m_querybutton->setFixedWidth(80);
    m_exportbutton->setFixedWidth(80);

    hboxlayout->addWidget(accountLabel);
    hboxlayout->addWidget(m_accountCombox);
    hboxlayout->addWidget(m_querybutton);
    //hboxlayout->addWidget(m_exportbutton);
    hboxlayout->addStretch();
    hboxlayout->addStretch();

    MainLayout = new QGridLayout(this);

    m_tableHold = new QTableView;
    m_tableHold->setAlternatingRowColors(true);
    QFont font = m_tableHold->horizontalHeader()->font();
    font.setBold(true);
    m_tableHold->horizontalHeader()->setFont(font);

    m_tableHold->setModel(m_modelHold);
    m_tableHold->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_tableHold->verticalHeader()->setVisible(false); //隐藏列表头
    m_tableHold->verticalHeader()->setFixedWidth(40);
    m_tableHold->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_tableHold->setSelectionMode(QAbstractItemView::SingleSelection);

    m_tableHold->setColumnWidth(0, 100);
    m_tableHold->setColumnWidth(1, 100);
    m_tableHold->setColumnWidth(2, 100);
    m_tableHold->setColumnWidth(3, 120);
    m_tableHold->setColumnWidth(4, 100);
    m_tableHold->setColumnWidth(5, 100);
    m_tableHold->setColumnWidth(6, 100);
    m_tableHold->setColumnWidth(7, 100);
    m_tableHold->setColumnWidth(8, 100);
    m_tableHold->setColumnWidth(9, 100);
    m_tableHold->setColumnWidth(10, 100);
    m_tableHold->setColumnWidth(11, 100);
    m_tableHold->setColumnWidth(12, 100);

    MainLayout->addLayout(hboxlayout,0,0);
    MainLayout->addWidget(m_tableHold,1,0);
    MainLayout->setMargin(20);
	//创建菜单、菜单项
	this->m_tableHold->setContextMenuPolicy(Qt::CustomContextMenu);
	m_RightPopMenu = new QMenu(this->m_tableHold);
	m_ShijiaAction = new QAction(QStringLiteral("市价平仓"),this); 
	m_DuijiaAction = new QAction(QStringLiteral("对价平仓"),this); 
	m_updateAction = new QAction(QStringLiteral("刷新"),this);
	m_outputAction = new QAction(QStringLiteral("导出"),this); 
	m_RightPopMenu->addAction(m_ShijiaAction);
	m_RightPopMenu->addAction(m_DuijiaAction);
	m_RightPopMenu->addAction(m_updateAction);
    //m_RightPopMenu->addAction(m_outputAction);
    //右键弹出菜单事件绑定
	connect(this->m_tableHold,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(RightClickedMenuPop(const QPoint&)));
	//查询按钮事件绑定
    connect(this->m_querybutton,SIGNAL(clicked()),this,SLOT(QueryButtonClicked()));
	//市价平仓事件绑定
	connect(m_ShijiaAction, SIGNAL(triggered()), this, SLOT(ShijiaAction()));
	//对价平仓事件绑定
	connect(m_DuijiaAction, SIGNAL(triggered()), this, SLOT(DuijiaAction()));
	//刷新事件绑定
	connect(m_updateAction, SIGNAL(triggered()), this, SLOT(UpdateHold()));
	//导出事件绑定
	connect(m_outputAction, SIGNAL(triggered()), this, SLOT(OutputHold()));
}
//市价平仓事件绑定
void MainHoldWidget::ShijiaAction(){
    QModelIndex index = m_tableHold->currentIndex();
    if (true == index.isValid()){//选中持仓
        int iRow = index.row();
        int iCnt = index.sibling(iRow,6).data().toString().toInt();//今日持仓数量
        if(iCnt > 0){
            CThostFtdcInputOrderField OrderInfo;
            memset(&OrderInfo, 0, sizeof(CThostFtdcInputOrderField));
            ///合约代码
            QString strContractID = index.sibling(iRow,1).data().toString();
            strncpy(OrderInfo.InstrumentID, strContractID.toStdString().c_str(), sizeof(TThostFtdcInstrumentIDType));
            ///买卖方向
            QString strBS = index.sibling(iRow,2).data().toString();
            if(strBS == QStringLiteral("多头")){
                OrderInfo.Direction = THOST_FTDC_D_Sell;///卖出
            }else if(strBS == QStringLiteral("空头")){
                OrderInfo.Direction = THOST_FTDC_D_Buy;///买入
            }
            ///报单价格条件类型：任意价
            OrderInfo.OrderPriceType = THOST_FTDC_OPT_AnyPrice;
            ///价格
            OrderInfo.LimitPrice = 0;
            ///有效期类型：立即完成，否则撤销
            OrderInfo.TimeCondition =   THOST_FTDC_TC_IOC;
            ///数量
            OrderInfo.VolumeTotalOriginal = iCnt;
            OnEntrust(OrderInfo);
        }else{
            QMessageBox::critical(this,QString("ERROR"),QStringLiteral("可平仓数量不足!"));
        }
    }else{
        QMessageBox::critical(this,QString("ERROR"),QStringLiteral("请选择有效持仓进行平仓!"));
    }
}
//对价平仓事件绑定
void MainHoldWidget::DuijiaAction(){
    QModelIndex index = m_tableHold->currentIndex();
    if (true == index.isValid()){//选中持仓
        int iRow = index.row();
        int iCnt = index.sibling(iRow,6).data().toString().toInt();//今日持仓数量
        if(iCnt > 0){
            CThostFtdcInputOrderField OrderInfo;
            memset(&OrderInfo, 0, sizeof(CThostFtdcInputOrderField));
            ///合约代码
            QString strContractID = index.sibling(iRow,1).data().toString();
            strncpy(OrderInfo.InstrumentID, strContractID.toStdString().c_str(), sizeof(TThostFtdcInstrumentIDType));
            ///买卖方向
            QString strBS = index.sibling(iRow,2).data().toString();
            if(strBS == QStringLiteral("多头")){
                OrderInfo.Direction = THOST_FTDC_D_Sell;///卖出
                OrderInfo.OrderPriceType = THOST_FTDC_OPT_BidPrice1;///买一价
            }else if(strBS == QStringLiteral("空头")){
                OrderInfo.Direction = THOST_FTDC_D_Buy;///买入
                OrderInfo.OrderPriceType = THOST_FTDC_OPT_AskPrice1;///卖一价
            }
            ///价格
            OrderInfo.LimitPrice = 0;
            ///有效期类型：立即完成，否则撤销
            OrderInfo.TimeCondition =   THOST_FTDC_TC_IOC;
            ///数量
            OrderInfo.VolumeTotalOriginal = iCnt;
            OnEntrust(OrderInfo);
        }else{
            QMessageBox::critical(this,QString("ERROR"),QStringLiteral("可平仓数量不足!"));
        }
    }else{
        QMessageBox::critical(this,QString("ERROR"),QStringLiteral("请选择有效持仓进行平仓!"));
    }
}
void MainHoldWidget::OnEntrust(CThostFtdcInputOrderField &OrderInfo){

    OrderInfo.CombOffsetFlag[0]='1';//平仓
    ///组合投机套保标志 //0投机；1套保
    //OrderInfo.CombHedgeFlag[0]=GetHedgeFlag(myOrder->Hedge);
    OrderInfo.CombHedgeFlag[0]='1'	;
    ///成交量类型 任意数量
    OrderInfo.VolumeCondition = THOST_FTDC_VC_AV;
    ///触发条件:立即
    OrderInfo.ContingentCondition = THOST_FTDC_CC_Immediately;
    ///最小成交量 1
    OrderInfo.MinVolume = 1;
    ///强平原因 非强平
    OrderInfo.ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
    ///自动挂起标志 否
    OrderInfo.IsAutoSuspend = 0;
    ///用户强平标志 否
    OrderInfo.UserForceClose = 0;

    emit OnOrderInsert(&OrderInfo);
}
//刷新事件绑定
void MainHoldWidget::UpdateHold(){
	this->QueryButtonClicked();
}
//导出事件绑定
void MainHoldWidget::OutputHold(){
    //暂未实现
}
//右键弹出菜单响应函数
void MainHoldWidget::RightClickedMenuPop(const QPoint& pos)
{
	m_RightPopMenu->exec(QCursor::pos());
}
//查询按钮响应函数
void MainHoldWidget::QueryButtonClicked(){
    m_HoldOrderVector.clear();
    m_modelHold->removeRows(0,m_modelHold->rowCount());
    emit ReqQryInvestorPosition(m_accountCombox->currentText());
}
void MainHoldWidget::ShowInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition){
	//将报单信息保存在Vector中
	CThostFtdcInvestorPositionField oOrder;
	memcpy_s(&oOrder,sizeof(CThostFtdcInvestorPositionField),pInvestorPosition,sizeof(CThostFtdcInvestorPositionField));
    m_HoldOrderVector.push_back(oOrder);

    int iRow = m_modelHold->rowCount();
    ///投资者代码
    ((QStandardItemModel*) m_modelHold)->setItem(iRow, 0, new QStandardItem(pInvestorPosition->InvestorID));
    ///合约代码
    ((QStandardItemModel*) m_modelHold)->setItem(iRow, 1, new QStandardItem(pInvestorPosition->InstrumentID));
    ///持仓多空方向
    switch(pInvestorPosition->PosiDirection){
    case THOST_FTDC_PD_Net:
        ((QStandardItemModel*) m_modelHold)->setItem(iRow, 2, new QStandardItem(QStringLiteral("净")));
        break;
    case THOST_FTDC_PD_Long:
        ((QStandardItemModel*) m_modelHold)->setItem(iRow, 2, new QStandardItem(QStringLiteral("多头")));
        break;
    case THOST_FTDC_PD_Short:
        ((QStandardItemModel*) m_modelHold)->setItem(iRow, 2, new QStandardItem(QStringLiteral("空头")));
        break;
    default:
        break;
    }
    ///投机套保标志
    switch(pInvestorPosition->HedgeFlag){
    case THOST_FTDC_HF_Speculation:
        ((QStandardItemModel*) m_modelHold)->setItem(iRow, 3, new QStandardItem(QStringLiteral("投机")));
        break;
    case THOST_FTDC_HF_Arbitrage:
        ((QStandardItemModel*) m_modelHold)->setItem(iRow, 3, new QStandardItem(QStringLiteral("套利")));
        break;
    case THOST_FTDC_HF_Hedge:
        ((QStandardItemModel*) m_modelHold)->setItem(iRow, 3, new QStandardItem(QStringLiteral("套保")));
        break;
    default:
        break;
    }
    ///持仓日期
    ((QStandardItemModel*) m_modelHold)->setItem(iRow, 4, new QStandardItem(pInvestorPosition->TradingDay));
    //上日持仓
    ((QStandardItemModel*) m_modelHold)->setItem(iRow, 5, new QStandardItem(QString::number(pInvestorPosition->YdPosition)));
    //今日持仓
    ((QStandardItemModel*) m_modelHold)->setItem(iRow, 6, new QStandardItem(QString::number(pInvestorPosition->Position)));
    //开仓量
    ((QStandardItemModel*) m_modelHold)->setItem(iRow, 7, new QStandardItem(QString::number(pInvestorPosition->OpenVolume)));
    //平仓量
    ((QStandardItemModel*) m_modelHold)->setItem(iRow, 8, new QStandardItem(QString::number(pInvestorPosition->CloseVolume)));
    //开仓金额
    ((QStandardItemModel*) m_modelHold)->setItem(iRow, 9, new QStandardItem(QString::number(pInvestorPosition->OpenAmount,'f')));
    //平仓金额
    ((QStandardItemModel*) m_modelHold)->setItem(iRow, 10, new QStandardItem(QString::number(pInvestorPosition->CloseAmount,'f')));
    //平仓盈亏
    ((QStandardItemModel*) m_modelHold)->setItem(iRow, 11, new QStandardItem(QString::number(pInvestorPosition->CloseProfit,'f')));
    //持仓盈亏
    ((QStandardItemModel*) m_modelHold)->setItem(iRow, 12, new QStandardItem(QString::number(pInvestorPosition->PositionProfit,'f')));
    //占用的保证金
    ((QStandardItemModel*) m_modelHold)->setItem(iRow, 13, new QStandardItem(QString::number(pInvestorPosition->UseMargin,'f')));
}
